<template>
  <!-- 原因分析:发生根本原因表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1000px"
    draggable
    @close="closeDialog"
    destroy-on-close
    :append-to-body="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160">
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button
            v-show="!props.isReadonly || !formData.id"
            type="success"
            plain
            @click="handleAdd"
          >
            <i-ep-plus />
            新增</el-button
          >
        </template>
        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />

            <el-table-column
              label="原因分析：为什么过程会发生这个缺陷？"
              props="exceptionContent"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.exceptionContent'"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.exceptionContent"
                    placeholder="请输入"
                    clearable
                    type="textarea"
                  />
                  <span v-else>{{ row.exceptionContent }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="exceptionContent" label-width="0">
            <template v-if="!props.isReadonly">
              <span>确认根本原因</span><br />
              <el-input
                v-model="formData.exceptionContent"
                type="textarea"
                placeholder="请输入"
                clearable
                :rows="6"
                style="min-height: 100px"
              />
            </template>
            <span v-else
              >确认根本原因<br />{{ formData.exceptionContent }}</span
            >
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin-top: 10px" v-if="loading1">
        <CommonUploadFile
          :isRead="props.isReadonly"
          :files="formData.assetPhotos"
          @update-files="updateFormFiles"
        />
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="success"
          :loading="loading"
          @click="handleSubmit(1)"
          >提 交</el-button
        >
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit(0)"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DD41ADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (!props.data?.id) {
      loading1.value = true;
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  qualityExceptionId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  qualityExceptionCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  exceptionContent: [
    {
      required: true,
      message: "确认根本原因",
      trigger: "blur",
    },
    { min: 1, max: 1000, message: "长度在 1 到 1000 个字符", trigger: "blur" },
  ],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);
const loading1 = ref(false);
let formData = reactive({
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  exceptionContent: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  assetPhotos: [],
  isSubmit: 0,
  workOrderId: "",
  details: [
    {
      id: "",
      qualityExceptionId: "",
      qualityExceptionCode: "",
      exceptionContent: "",
      version: "",
      remarks: "",
      createdUserName: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  formRef.value.clearValidate();
};
/** 添加行 */
const handleAdd = () => {
  let sondata = {}; // 创建一个空对象
  formData.details.push(sondata);
};
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        exceptionContent,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos,
      } = newVal;
      Object.assign(formData, {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        exceptionContent,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos: assetPhotos ?? [],
      });
      formData.qualityExceptionId = newVal.qualityProblemId;
      formData.qualityExceptionCode = newVal.qualityProblemCode;
      formData.workOrderId = newVal.id;
      loading1.value = false;
      getD41(newVal.id);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
const details = {
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  exceptionContent: "",
  version: "",
  remarks: "",
  createdUserName: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.qualityExceptionId = "";
  formData.qualityExceptionCode = "";
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.exceptionContent = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.assetPhotos = [];
  formData.isSubmit = 0;
  formData.workOrderId = "";
}

const loading = ref(false);

/** 原因分析:发生根本原因保存提交 */
function handleSubmit(state: Number) {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.isSubmit = state;
      await request({
        url: "/qms/q8dd41/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
// 图片处理
function updateFormFiles(val: []) {
  formData.assetPhotos = val;
}
const getD41 = async (id: string) => {
  if (id) {
    console.log("ids", id);
    await request({
      url: "/qms/q8dd41/getD41",
      method: "post",
      data: {
        workOrderId: id,
      },
    })
      .then((res) => {
        if (res.data != null) {
          Object.assign(formData, res.data);
          loading1.value = true;
        } else {
          formData.id = "";
          loading1.value = true;
        }
      })
      .finally(() => {
        loading1.value = true;
      });
  } else {
    loading1.value = true;
  }
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
